package com.nuist.controller;

import com.nuist.entity.Electric;
import com.nuist.result.Result;
import com.nuist.service.ElectricService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/16 23:32
 */
@RestController
@RequestMapping(value = "/electric")
@Slf4j
@Api(tags = "电器相关接口")
public class ElectricController {
    @Resource
    private ElectricService electricService;

    /**
     * 返回所有的电器信息(加入/查询redis缓存 key = Electric)
     *
     * @return
     */
    @Cacheable(cacheNames = "Electric",key = "'allElectric'")
    @ApiOperation(value = "返回所有的电器信息")
    @GetMapping(value = "/list")
    public Result<List<Electric>> selectAll() {
        List<Electric> electrics = electricService.list();
        return Result.success(electrics);
    }

    /**
     * 保存电器数据
     *
     * @param electric
     * @return
     */
    @ApiOperation(value = "保存电器数据")
    @PostMapping(value = "/save")
    public Result save(@RequestBody Electric electric) {
        System.out.println(electric);
        Electric electric1 = electricService.getById(electric.getId());
        // 不存在则新增电器
        if (electric1 == null) {
            electricService.saveElectric(electric);
            return Result.success();
        } else {                    // 存在则更新电器最新信息
            electricService.updateElectric(electric);
            return Result.success();
        }
    }
}
